package com.clouddisk.file.decorator.impl;

import com.clouddisk.file.decorator.FileHandlerDecorator;
import com.clouddisk.file.strategy.FileHandler;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 文件加密装饰器
 */
public class EncryptionDecorator extends FileHandlerDecorator {

    private static final String ALGORITHM = "AES";
    private static final String SECRET_KEY = "your-secret-key"; // 实际应用中应该从配置中获取

    public EncryptionDecorator(FileHandler fileHandler) {
        super(fileHandler);
    }

    @Override
    public String handleUpload(MultipartFile file) {
        try {
            // 加密文件内容
            byte[] encrypted = encrypt(file.getBytes());
            // TODO: 上传加密后的文件
            return super.handleUpload(file);
        } catch (Exception e) {
            throw new RuntimeException("文件加密失败", e);
        }
    }

    @Override
    public byte[] handlePreview(String storagePath) {
        try {
            // 获取加密的文件内容并解密
            byte[] encrypted = super.handlePreview(storagePath);
            return decrypt(encrypted);
        } catch (Exception e) {
            throw new RuntimeException("文件解密失败", e);
        }
    }

    private byte[] encrypt(byte[] data) throws Exception {
        SecretKey secretKey = generateSecretKey();
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(data);
    }

    private byte[] decrypt(byte[] encryptedData) throws Exception {
        SecretKey secretKey = generateSecretKey();
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return cipher.doFinal(encryptedData);
    }

    private SecretKey generateSecretKey() throws NoSuchAlgorithmException {
        // 在实际应用中，应该使用更安全的密钥管理方式
        return new SecretKeySpec(
            Base64.getDecoder().decode(SECRET_KEY),
            ALGORITHM
        );
    }
} 